package com.ligq.vbasedemo.fragment

import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import com.ligq.vbasedemo.R
import com.ligq.vbasedemo.decode.H264Player
import java.io.IOException

class H264DecodeFragment : BaseFragment() {
    private var player: H264Player? = null
    private var callBack: SurfaceHolder.Callback? = null
    override fun initView(view: View?) {
        val preview: SurfaceView = view?.findViewById(R.id.preview)!!
        addSurfaceCallback(preview)
//        preview.setOnClickListener {
//            player?.stop()
//            addSurfaceCallback(preview)
//        }
    }

    private fun addSurfaceCallback(preview: SurfaceView) {
        if (callBack != null) {
            preview.holder.removeCallback(callBack)
        }
        callBack = object : SurfaceHolder.Callback {
            override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
                try {
                    player = H264Player(
                        context!!.assets.open("output.h264"),
                        surfaceHolder.surface
                    )
                    player?.start()
                } catch (e: IOException) {
                    Log.e("TAG", "surfaceCreated: ", e)
                }
            }

            override fun surfaceChanged(
                surfaceHolder: SurfaceHolder,
                i: Int,
                i1: Int,
                i2: Int
            ) {
            }

            override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {}
        }
        preview.holder.addCallback(callBack)
    }

    override fun getLayoutId(): Int = R.layout.fragment_h264_decode

    override fun onStop() {
        Log.d("ligq", "onStop: 停止播放")
        player?.stop()
        super.onStop()
    }
}